import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { JsonApiService } from "app/core/api/json-api.service";
import {config} from '../../shared/smartadmin.config';

declare var $: any;
interface Person {
	polishInstallerName: any,
	patchInstallerName: any
	threadingInstallerName: any
	hostInstallerName: any
	sealantInstallerName: any
}
@Component({
	selector: 'sa-record-page',
	templateUrl: './record-page.component.html',
})
export class RecordPageComponent implements OnInit {
	validatorOptions = {
		excluded:[":disabled"],
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			carNumberInput: {
				trigger:"change",
				validators: {
					notEmpty: {
						message: '请选择车牌号码'
					}
				}
			},
			polishInstaller: {
				validators: {
					notEmpty: {
						message: '请选择打磨清洗人'
					}
				}
			},
			patchInstaller: {
				validators: {
					notEmpty: {
						message: '请选择贴片人'
					}
				}
			},
			sealantInstaller: {
				validators: {
					notEmpty: {
						message: '请选择封胶人'
					}
				}
			},
			threadingInstaller: {
				validators: {
					notEmpty: {
						message: '请选择穿线人'
					}
				}
			},
			hostInstaller: {
				validators: {
					notEmpty: {
						message: '请选择安装主机人'
					}
				}
			},
			startInstallTime:{
				trigger:"change",
				validators: {
					notEmpty: {
						message: '请选择开始安装时间'
					},
					date: {
                        format: 'YYYY-MM-DD h:m:s',
                        message: '请输入正确的时间,例如2018-01-00 00:00:00'
                    }
				}
			},
			installTime:{
				trigger:"change",
				validators: {
					notEmpty: {
						message: '请选择完成安装时间'
					},
					date: {
                        format: 'YYYY-MM-DD h:m:s',
                        message: '请输入正确的时间,例如2018-01-00 00:00:00'
                    }
				}
			}
		}
	};
	page: any = {
		deviceId:'',
		carNumber: '',
		polishInstaller:'',
		patchInstaller:'',
		sealantInstaller:'',
		threadingInstaller:'',
		hostInstaller:'',
		startInstallTime:'',
		installTime:'',
		installAddress: '',
		recorder:'',
		auditStatus:null,
		auditorUser:'',
		auditorTime:'',
	};
	auditStatusList = [{
		label:'未审核',
		value:0
	},{
		label:'审核通过',
		value:1
	},{
		label:'审核不通过',
		value:2
	}];
	userList:any;
	page_title:string = '新增';
	pageType:string = 'new';
	recordId = null;
	submitted = false;
	timer:any;
	curPage = 0;

	constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.recordId = queryParams.id;
			this.pageType = queryParams.type;
			this.curPage = queryParams.nowPage;
		});
	}
	//审核状态change回调事件
	auditStatusChange(val){
		if(val === '0'){
			this.page.auditorUser = '';
			$('#auditorTime').val('');
		}else{
			this.initDate();
		}
		this.page.auditStatus = parseInt(val);
	}
	onSubmit(){
		$('#recordForm').bootstrapValidator('validate'); //开启验证
		let isValid = $('#recordForm').data('bootstrapValidator').isValid();  //验证是否通过
		if(isValid){
			this.updata();
		}
	}
	getSelect2Value(id){
		var data = $(id).select2("data");
		var result = '';
		for(let item of data){
			result += item.id+",";
		}
		result = result.substring(0,result.length-1);
		return result;
	}
	updata(){
		if(this.page.auditStatus === 0){
			this.page.auditorUser = '';
			this.page.auditorTime = '';
		}
		this.page.startInstallTime = $('#startInstallTime').val();
		this.page.installTime = $('#installTime').val();
		this.page.polishInstaller = this.getSelect2Value('#polishSelect2');
		this.page.patchInstaller = this.getSelect2Value('#patchSelect2');
		this.page.sealantInstaller = this.getSelect2Value('#sealantSelect2');
		this.page.threadingInstaller = this.getSelect2Value('#threadingSelect2');
		this.page.hostInstaller = this.getSelect2Value('#hostSelect2');
		var reqdata = '',url;
		if(this.pageType === 'new'){
			reqdata = 'carNumber='+this.page.carNumber+'&deviceId='+this.page.deviceId+'&polishInstaller='+this.page.polishInstaller+'&polishInstallerName='+this.person.polishInstallerName.join(',')+'&patchInstallerName='+this.person.patchInstallerName.join(',')+'&sealantInstallerName='+this.person.sealantInstallerName.join(',')+'&threadingInstallerName='+this.person.threadingInstallerName.join(',')+'&hostInstallerName='+this.person.hostInstallerName.join(',')+'&patchInstaller='+this.page.patchInstaller+'&sealantInstaller='+this.page.sealantInstaller+'&threadingInstaller='+this.page.threadingInstaller+
						'&hostInstaller='+this.page.hostInstaller+'&startInstallTime='+this.page.startInstallTime+'&installTime='+this.page.installTime+'&installAddress='+this.page.installAddress;
			url = 'deviceInstall/insertDeviceInstall.html';
		}else if(this.pageType === 'updata'){
			reqdata = 'id='+this.recordId+'&deviceId='+this.page.deviceId+'&carNumber='+this.page.carNumber+'&polishInstaller='+this.page.polishInstaller+'&polishInstallerName='+this.person.polishInstallerName.join(',')+'&patchInstallerName='+this.person.patchInstallerName.join(',')+'&sealantInstallerName='+this.person.sealantInstallerName.join(',')+'&threadingInstallerName='+this.person.threadingInstallerName.join(',')+'&hostInstallerName='+this.person.hostInstallerName.join(',')+'&sealantInstaller='+this.page.sealantInstaller+'&patchInstaller='+this.page.patchInstaller+'&threadingInstaller='+this.page.threadingInstaller+
						'&hostInstaller='+this.page.hostInstaller+'&startInstallTime='+this.page.startInstallTime+'&installTime='+this.page.installTime+'&installAddress='+this.page.installAddress+'&recorder='+this.page.recorder+'&auditStatus='+this.page.auditStatus+
						'&auditorUser='+this.page.auditorUser+'&auditorTime='+this.page.auditorTime;
			url = 'deviceInstall/updateDeviceInstall.html';
		}
		this.jsonApiService.http(url,reqdata).subscribe(data=> {
			this.jsonApiService.message(data.message);
			if(data.success){
				this.router.navigate(['/device-management/record'],{ queryParams: {nowPage:this.curPage}});
			}
		})
	}
	//	返回资源列表页
	goBack() {
		this.router.navigate(['/device-management/record'],{ queryParams: {nowPage:this.curPage}});
	}
	//初始化车辆
	initCar(){
		var that = this;
		$("#carNumberSelect2").select2({
            language : "zh-CN",
            minimumInputLength: 2,
			allowClear: true,
			placeholder:"请选择",
			ajax: {
	    		url: config.BaseURL+"stats/carListByCarNumber.html",
	    		dataType: 'json',
	    		delay: 50,
	    		method: "POST",
	    		xhrFields: {withCredentials: true},
	    		data: function (params){return {"carNumber" :  params.term};},
	    		processResults: function(data, params) {
					var options = new Array();
					// 小于10个数量才判断重复
					if(data.data.length<=10){
						let arr = []
						let sameCar = []
						// 判断相同的车牌号
						for (let index = 0; index < data.data.length; index++) {
							let car = data.data[index];
							if(arr.indexOf(car.carNumber)!=-1){
								sameCar.push(car.carNumber)
							}else{
								arr.push(car.carNumber);
							}
						}
						$(data.data).each(function(index, car) {
							if(sameCar.indexOf(car.carNumber)!=-1){
								options.push({
									id: car.deviceId,
									text: car.carNumber+"["+car.parentName+"]"
								})
							}else{
								options.push({
									id: car.deviceId,
									text: car.carNumber
								})
							}
						});
					}else{
						$(data.data).each(function(index, car) {
							options.push({
								id: car.deviceId,
								text: car.carNumber
							})
						});
					}
					return {
						results: options //获取查询后的结果
					};
				},
	    		cache: true
	        },
            templateResult : function (state){
            	if (!state.id) {return state.text;}
                var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
                return $state;
            },
       }).on("select2:select", function (e){
        	var data = e.params.data;
			that.page.deviceId = data.id;
			if(data.text.indexOf('[') > 0){
				that.page.carNumber = data.text.split('[')[0];
			} else {
				that.page.carNumber = data.text;
			}
        	$("#carNumberInput").val(that.page.carNumber).change();
        });
	
	}
	initAllUser(){
		var that = this;
		return new Promise(function (resolve, reject) {
			that.jsonApiService.http("user/getAllUserList.html",null).subscribe(data=> {
				if(data.success){
					var userList = data.data;
		        	var selectdata = [];
		        	for(var i = 0 ; i < userList.length ; i++) {
		        		var obj = {
		        			id:userList[i].id,
		        			text:userList[i].name,
		        		}
		        		selectdata[i] = obj;
		        	}
				}
				that.userList = selectdata;
				resolve();
			})
		})
	}

	person: Person = {
		polishInstallerName: [],
		patchInstallerName: [],
		threadingInstallerName: [],
		hostInstallerName: [],
		sealantInstallerName: [],
	}
	initAllSelect2(){
		const that = this
		$("#polishSelect2").select2({
			language : "zh-CN",
            data: this.userList
       	}).on("select2:select", function (e){
        	var data = e.params.data;
        	$("#polishInstallerInput").val(data.text).change();
			that.person.polishInstallerName.push(data.text)
			that.person.polishInstallerName = Array.from(new Set(that.person.polishInstallerName))
        }).on("select2:unselect", function (e){
			var data = e.params.data;
			for (let i = 0, len = that.person.polishInstallerName.length; i < len; i++) {
				if (that.person.polishInstallerName[i] === data.text) {
					that.person.polishInstallerName.splice(i, 1);
					break
				}
			}
		});
        $("#patchSelect2").select2({
        	language : "zh-CN",
            data: this.userList
        }).on("select2:select", function (e){
        	var data = e.params.data;
        	$("#patchInstallerInput").val(data.text).change();
			that.person.patchInstallerName.push(data.text)
			that.person.patchInstallerName = Array.from(new Set(that.person.patchInstallerName))
        }).on("select2:unselect", function (e){
			var data = e.params.data;
			for (let i = 0, len = that.person.patchInstallerName.length; i < len; i++) {
				if (that.person.patchInstallerName[i] === data.text) {
					that.person.patchInstallerName.splice(i, 1);
					break
				}
			}
		});
        $("#sealantSelect2").select2({
        	language : "zh-CN",
            data: this.userList
        }).on("select2:select", function (e){
        	var data = e.params.data;
        	$("#sealantInstallerInput").val(data.text).change();
			that.person.sealantInstallerName.push(data.text)
			that.person.sealantInstallerName = Array.from(new Set(that.person.sealantInstallerName))
        }).on("select2:unselect", function (e){
			var data = e.params.data;
			for (let i = 0, len = that.person.sealantInstallerName.length; i < len; i++) {
				if (that.person.sealantInstallerName[i] === data.text) {
					that.person.sealantInstallerName.splice(i, 1);
					break
				}
			}
		});
        $("#threadingSelect2").select2({
        	language : "zh-CN",
            data: this.userList
        }).on("select2:select", function (e){
        	var data = e.params.data;
        	$("#threadingInstallerInput").val(data.text).change();
			that.person.threadingInstallerName.push(data.text)
			that.person.threadingInstallerName = Array.from(new Set(that.person.threadingInstallerName))
        }).on("select2:unselect", function (e){
			var data = e.params.data;
			for (let i = 0, len = that.person.threadingInstallerName.length; i < len; i++) {
				if (that.person.threadingInstallerName[i] === data.text) {
					that.person.threadingInstallerName.splice(i, 1);
					break
				}
			}
		});
        $("#hostSelect2").select2({
        	language : "zh-CN",
            data: this.userList
        }).on("select2:select", function (e){
        	var data = e.params.data;
        	$("#hostInstallerInput").val(data.text).change();
			that.person.hostInstallerName.push(data.text)
			that.person.hostInstallerName = Array.from(new Set(that.person.hostInstallerName))
        }).on("select2:unselect", function (e){
			var data = e.params.data;
			for (let i = 0, len = that.person.hostInstallerName.length; i < len; i++) {
				if (that.person.hostInstallerName[i] === data.text) {
					that.person.hostInstallerName.splice(i, 1);
					break
				}
			}
		});
	}
	//初始化日期
	initDate(){
		System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(
			()=>{System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(()=>{
				common.initDatePicker("#auditorTime",0);
				$("#startInstallTime").datetimepicker({//时间插件
					format: "yyyy-mm-dd hh:ii:ss",
				    language: "zh-CN",
				    autoclose: true,
				}).on("changeDate", function(e){
					var date = e.date;
					if(!date){return;}
					var time = common.getTimeMmss(date);
					$("#installTime").datetimepicker("setStartDate", time);
				});
				$("#installTime").datetimepicker({//时间插件
					format: "yyyy-mm-dd hh:ii:ss",
				    language: "zh-CN",
				    autoclose: true,
				}).on("changeDate", function(e){
					var date = e.date;
					if(!date){return;}
					var time = common.getTimeMmss(date);
					$("#startInstallTime").datetimepicker("setEndDate", time);
				});
			});
		});
	}
	ngOnInit(){
		this.initDate();
		System.import('script-loader!select2/dist/js/select2.min.js').then(()=>{
			System.import('assets/js/select2-zh-CN.js').then(()=>{
				this.initCar();
				this.initAllSelect2();
				this.initAllUser().then(()=>{
					this.initAllSelect2();
					if(this.pageType === 'updata') {
						this.page_title = '编辑';
						let reqdata = 'id='+this.recordId;
						this.jsonApiService.http("deviceInstall/getDeviceInstallById.html",reqdata).subscribe(data=> {
							if(data.success){
								for(let item in this.page){
									if(item === 'auditStatus'){
										this.page[item] = data.data[item];
									}else{
										this.page[item] = data.data[item]?data.data[item]:'';
									}
								}
								for (const item in this.person) {
									if(item === 'auditStatus'){
										this.person[item] = data.data[item].split(',')
									} else {
										this.person[item] = data.data[item] ? data.data[item].split(',') : []
									}
								}
								this.setSelect2Value();
							}else{
								this.jsonApiService.message(data.message);
							}
							
						})
					}
				});
			})
		});
		
	}
	//select2赋值
	setSelect2Value(){
		var tempolishInstallerArr=this.page.polishInstaller.split(','),
			tempatchInstallerArr=this.page.patchInstaller.split(','),
			temsealantInstallerArr=this.page.sealantInstaller.split(','),
			temthreadingInstallerArr=this.page.threadingInstaller.split(','),
			temhostInstallerArr=this.page.hostInstaller.split(',');
		$('#carNumberSelect2').val(this.page.deviceId).trigger('change');
		$('#polishSelect2').val(tempolishInstallerArr).trigger('change');
		$('#patchSelect2').val(tempatchInstallerArr).trigger('change');
		$('#sealantSelect2').val(temsealantInstallerArr).trigger('change');
		$('#threadingSelect2').val(temthreadingInstallerArr).trigger('change');
		$('#hostSelect2').val(temhostInstallerArr).trigger('change');
	}

}